package com.luxuewen.sxa.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luxuewen.sxa.entity.SxaDepartmentUsers;
import com.luxuewen.sxa.entity.SxaUserRoles;
import com.luxuewen.sxa.entity.SxaUsers;
import com.luxuewen.sxa.entity.response.UserListRes;
import com.luxuewen.sxa.common.enums.ResponseEnum;
import com.luxuewen.sxa.common.exception.ApiException;
import com.luxuewen.sxa.service.SxaUsersService;
import com.luxuewen.sxa.mapper.SxaUsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
* @author wen
* @description 针对表【sxa_users】的数据库操作Service实现
* @createDate 2023-11-01 16:17:09
*/
@Service
public class SxaUsersServiceImpl extends ServiceImpl<SxaUsersMapper, SxaUsers>
    implements SxaUsersService{
    @Autowired
    private SxaDepartmentUsersServiceImpl sxaDepartmentUsersService;

    @Autowired
    private SxaUserRolesServiceImpl sxaUserRolesService;

    @Autowired
    private SxaUsersMapper sxaUsersMapper;

    @Transactional(rollbackFor = Exception.class)
    public SxaUsers create (SxaUsers sxaUsers) {
        // 用户名检查
        QueryWrapper<SxaUsers> wrapper = new QueryWrapper<>();
        wrapper.eq("username", sxaUsers.getUsername());

        boolean sxaUsersExists = this.exists(wrapper);
        if (sxaUsersExists) {
            throw new ApiException(ResponseEnum.PARAM_ERROR.getCode(), "用户名已存在，请更换后再试！");
        }

        // 密码处理
        String pwd = sxaUsers.getPassword();
        if (!Objects.equals(pwd, sxaUsers.getPasswordConfirmation())) {
            throw new ApiException(ResponseEnum.PARAM_ERROR.getCode(), "密码和确认密码不一致，请检查后再提交！");
        }
        sxaUsers.setPassword(BCrypt.hashpw(pwd, BCrypt.gensalt()));

        // 创建用户
        boolean sxaUserRes = this.save(sxaUsers);
        if (!sxaUserRes) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "用户添加失败！");
        }

        // 保存部门
        List<SxaDepartmentUsers> sxaDepartmentUsersList = new ArrayList<>();

        int[] departmentIds = sxaUsers.getDepartmentIds();
        for (int departmentId : departmentIds) {
            SxaDepartmentUsers sxaDepartmentUsers = new SxaDepartmentUsers();

            sxaDepartmentUsers.setDepartmentId(departmentId);
            sxaDepartmentUsers.setUserId(sxaUsers.getId());

            sxaDepartmentUsersList.add(sxaDepartmentUsers);
        }
        boolean sxaDepartmentUsersRes = sxaDepartmentUsersService.saveBatch(sxaDepartmentUsersList);
        if (!sxaDepartmentUsersRes) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "用户部门保存失败！");
        }

        // 保存角色
        List<SxaUserRoles> sxaUserRolesList = new ArrayList<>();

        int[] roleIds = sxaUsers.getRoleIds();
        for (int roleId : roleIds) {
            SxaUserRoles sxaUserRoles = new SxaUserRoles();

            sxaUserRoles.setRoleId(roleId);
            sxaUserRoles.setUserId(sxaUsers.getId());

            sxaUserRolesList.add(sxaUserRoles);
        }
        boolean sxaUserRoleRes = sxaUserRolesService.saveBatch(sxaUserRolesList);
        if (!sxaUserRoleRes) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "用户角色保存失败！");
        }

        return sxaUsers;
    }

    @Transactional
    public SxaUsers update (SxaUsers sxaUsers) {
        // 用户名检查
        QueryWrapper<SxaUsers> wrapper = new QueryWrapper<>();
        wrapper.ne("id", sxaUsers.getId()).eq("username", sxaUsers.getUsername());

        boolean sxaUsersExists = this.exists(wrapper);
        if (sxaUsersExists) {
            throw new ApiException(ResponseEnum.PARAM_ERROR.getCode(), "用户名已存在，请更换后再试！");
        }

        // 用户合理性检查
        SxaUsers sxaUsers1 = this.getById(sxaUsers.getId());
        if (sxaUsers1 == null) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "未找到当前用户！");
        }

        // 密码处理
        String pwd = sxaUsers.getPassword();
        if (!Objects.equals(pwd, sxaUsers.getPasswordConfirmation())) {
            throw new ApiException(ResponseEnum.PARAM_ERROR.getCode(), "密码和确认密码不一致，请检查后再提交！");
        }

        if (!Objects.equals(sxaUsers1.getPassword(), sxaUsers.getPassword())) {
            sxaUsers.setPassword(BCrypt.hashpw(pwd, BCrypt.gensalt()));
        }

        // 更新用户
        boolean res = this.updateById(sxaUsers);
        if (!res) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "用户修改失败！");
        }

        // 清除原有部门关系
        QueryWrapper<SxaDepartmentUsers> sxaDepartmentUsersQueryWrapper = new QueryWrapper<>();
        sxaDepartmentUsersQueryWrapper.eq("user_id", sxaUsers.getId());
        boolean deptEx = sxaDepartmentUsersService.exists(sxaDepartmentUsersQueryWrapper);
        if (deptEx) {
            boolean deptDel = sxaDepartmentUsersService.remove(sxaDepartmentUsersQueryWrapper);
            if (!deptDel) {
                throw new ApiException(ResponseEnum.FAILURE.getCode(), "清除用户原有部门关系失败！");
            }
        }

        // 保存部门
        List<SxaDepartmentUsers> sxaDepartmentUsersList = new ArrayList<>();

        int[] departmentIds = sxaUsers.getDepartmentIds();
        for (int departmentId : departmentIds) {
            SxaDepartmentUsers sxaDepartmentUsers = new SxaDepartmentUsers();

            sxaDepartmentUsers.setDepartmentId(departmentId);
            sxaDepartmentUsers.setUserId(sxaUsers.getId());

            sxaDepartmentUsersList.add(sxaDepartmentUsers);
        }
        boolean sxaDepartmentUsersRes = sxaDepartmentUsersService.saveBatch(sxaDepartmentUsersList);
        if (!sxaDepartmentUsersRes) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "用户部门保存失败！");
        }

        // 清除用户原有角色关系
        QueryWrapper<SxaUserRoles> sxaUserRolesQueryWrapper = new QueryWrapper<>();
        sxaUserRolesQueryWrapper.eq("user_id", sxaUsers.getId());
        boolean roleEx = sxaUserRolesService.exists(sxaUserRolesQueryWrapper);
        if (roleEx) {
            boolean roleDel = sxaUserRolesService.remove(sxaUserRolesQueryWrapper);
            if (!roleDel) {
                throw new ApiException(ResponseEnum.FAILURE.getCode(), "清除用户原有角色关系失败！");
            }
        }

        // 保存角色
        List<SxaUserRoles> sxaUserRolesList = new ArrayList<>();

        int[] roleIds = sxaUsers.getRoleIds();
        for (int roleId : roleIds) {
            SxaUserRoles sxaUserRoles = new SxaUserRoles();

            sxaUserRoles.setRoleId(roleId);
            sxaUserRoles.setUserId(sxaUsers.getId());

            sxaUserRolesList.add(sxaUserRoles);
        }
        boolean sxaUserRoleRes = sxaUserRolesService.saveBatch(sxaUserRolesList);
        if (!sxaUserRoleRes) {
            throw new ApiException(ResponseEnum.FAILURE.getCode(), "用户角色保存失败！");
        }

        return sxaUsers;
    }

    public UserListRes userInfo (String username) {
        QueryWrapper<SxaUsers> sxaUsersQueryWrapper = new QueryWrapper<>();
        sxaUsersQueryWrapper.eq("a.username", username).eq("a.status", 1).isNull("a.deleted_at");

        return sxaUsersMapper.userInfo(sxaUsersQueryWrapper);
    }

    public Page<UserListRes> userList (Integer deptId, long page, long limit, String name) {
        QueryWrapper<SxaUsers> sxaUsersQueryWrapper = new QueryWrapper<>();
        sxaUsersQueryWrapper.isNull("a.deleted_at");

        // 用户列表搜索用户名/姓名
        if (!name.isEmpty()) {
            sxaUsersQueryWrapper.and(i->i.like("a.name", name).or().like("a.username", name));
        }

        if (deptId > 0) {
            sxaUsersQueryWrapper.inSql("id", "select user_id from sxa_department_users where department_id = " + deptId);
        }

        Page<UserListRes> sxaUsersPage = new Page<>(page, limit);
        return sxaUsersMapper.userList(sxaUsersPage, sxaUsersQueryWrapper);
    }
}




